package com.iseastar.guojiang.print;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.AppCaptureActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.BluetoothDeviceBean;
import com.iseastar.guojiang.model.PrintBean;
import com.iseastar.guojiang.model.PrintParcelBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.print.adapter.PrintAdapter;
import com.iseastar.guojiang.util.BluetoothUtils;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import droid.frame.activity.title.TitleRes;
import droid.frame.ui.dialog.AppDialog;
import droid.frame.utils.Android;
import droid.frame.view.xlist.SListView;

/**
 * Created by joker on 2017/7/25.
 * 面单打印
 */
public class PrintFragment extends BaseFragment implements View.OnClickListener {

    private SListView mListView;
    private RelativeLayout mSystemSettingRL;//进入系统设置页面
    private EditText mSerachParcelET;//通过投递编号条形码搜索打印
    private TextView mParcelCountTV;//当前包裹数量
    private PrintAdapter mAdapter = null;
    private BluetoothDeviceBean bluetoothDeviceBean = null;

    @Override
    protected void findViewById() {
        setContentView(R.layout.fragment_orderprint);
        super.findViewById();
        getAppTitle().setTitle(null, new TitleRes("面单打印"), null);
        mSystemSettingRL = (RelativeLayout) findViewById(R.id.systemsetting_RL);
        mSerachParcelET = (EditText) findViewById(R.id.serach_parcel_ET);
        mParcelCountTV = (TextView) findViewById(R.id.parcelcount_TV);
        mListView = (SListView) findViewById(R.id.listview);
        mSystemSettingRL.setOnClickListener(this);
        mSerachParcelET.setOnClickListener(this);
        findViewById(R.id.print_scan_IV).setOnClickListener(this);
        findViewById(R.id.submit_BT).setOnClickListener(this);
        mAdapter = new PrintAdapter(null, getActivityContext(), mListView);
        mListView.setAdapter(mAdapter);

        connectionDevice();

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                AppHttp.getInstance().getPrintOrderData();
            }
        });
        AppHttp.getInstance().getPrintOrderData();
    }

    @Override
    public void onResume() {
        super.onResume();
        bluetoothDeviceBean = AppCache.getBluetoothDeviceBean();
        if (!BluetoothUtils.isOpen() && mSystemSettingRL != null) {
            mSystemSettingRL.setVisibility(View.VISIBLE);
        }
    }

    public void connectionDevice() {
        if (BluetoothUtils.isOpen()) {
            bluetoothDeviceBean = AppCache.getBluetoothDeviceBean();
            if (bluetoothDeviceBean != null) {
                Intent intent = new Intent(getActivityContext(), BluetoothConnectionService.class);
                intent.setPackage(getActivityContext().getPackageName());
                intent.putExtra("status", 0);
                getActivityContext().startService(intent);
            } else {
                mSystemSettingRL.setVisibility(View.VISIBLE);
            }
        } else {
            mSystemSettingRL.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //点击设置跳到蓝牙设置界面
            case R.id.systemsetting_RL:
                intent = new Intent(getActivityContext(), BluetoothSettingActivity.class);
                intent.putExtra("from", 0);
                startActivityForResult(intent, 102);
                break;
            //点击输入框获取焦点
            case R.id.serach_parcel_ET:
                mSerachParcelET.setFocusable(true);
                mSerachParcelET.setFocusableInTouchMode(true);
                mSerachParcelET.requestFocus();
                setSoftInput(mSerachParcelET, true);
                break;
            //扫码袋子编号条形码
            case R.id.print_scan_IV:
                intent = new Intent();
                intent.setClass(getActivityContext(), AppCaptureActivity.class);
                startActivityForResult(intent, Const.RequestCode.scan_bag);
                break;
            //点击确定进行打印
            case R.id.submit_BT:
                //点击打印是先判断搜索框中的内容是否为投递编号的条形码,如果是，直接请求服务器打印相对于条形码对应的电子面单
                if (TextUtils.isEmpty(mSerachParcelET.getText()) == false && mSerachParcelET.getText().length() >= 10) {
                    mSerachParcelET.setFocusable(false);
                    mSerachParcelET.setFocusableInTouchMode(false);
                    mSerachParcelET.clearFocus();
                    Android.hideSoftInput(getActivityContext());
                    showLoadingDialog(null);
                    AppHttp.getInstance().queryParcelByBagCode(mSerachParcelET.getText().toString());
                } else {
                    showToast("输入的条形码有误");
                }
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //获取打印面单的数据
            case MsgID.query_printorder_data:
                onRefreshComplete();
                final ReqResult<PrintParcelBean> reqResult = JSON.parseList(msg.obj, PrintParcelBean.class);
                if (checkLoginStatus(reqResult)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.setItems(reqResult.getResultList(), true);
                            mParcelCountTV.setText("当前共" + mAdapter.getItemsSize() + "个包裹");
                        }
                    });
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            //根据袋子条形码查询对应的包裹信息
            case MsgID.queryparcel_by_bagcode:
                cancelLoadingDialog();
                final ReqResult<PrintBean> result = JSON.parser(msg.obj, PrintBean.class);
                if (checkLoginStatus(result)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (null != bluetoothDeviceBean && BluetoothConnectionService.iPrinter.connect(bluetoothDeviceBean.getDeviceName(), bluetoothDeviceBean.getDeviceAddress())) {
                                if (BluetoothConnectionService.iPrinter.isConnected()) {
                                    final PrintBean printBean = result.getResult();
                                    if (printBean.getIsPrinted() == 1) {//已经打印
                                        final AppDialog dialog = new AppDialog(getActivityContext(), true);
                                        dialog.setTitle("该包裹已经打印面单，是否重新打印?");
                                        dialog.show();
                                        dialog.setCancelClickListener("取消", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                            }
                                        });
                                        dialog.setConfirmClickListener("重新打印", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                                printData(printBean);
                                            }
                                        });
                                    } else {
                                        printData(printBean);
                                    }
                                } else {
                                    showToast("打印机连接失败");
                                }
                            } else {
                                showToast("打印机连接失败");
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            case MsgID.parcel_print_result:
                final ReqResult<?> result1 = JSON.parser(msg.obj);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result1)) {
                            mSerachParcelET.setText("");
                            AppHttp.getInstance().getPrintOrderData();
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });
                return true;
            case MsgID.bluetoothconnectinstatus:
                int status = (int) msg.obj;
                if (status == 0) {
                    mSystemSettingRL.setVisibility(View.GONE);
                } else {
                    mSystemSettingRL.setVisibility(View.VISIBLE);
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    private void printData(PrintBean printBean) {
        if (printBean.getExpressCompany().contains("韵达") || printBean.getExpressCompany().contains("圆通") || printBean.getExpressCompany().contains("申通") || printBean.getExpressCompany().contains("中通")) {
            if (PrintDataUtils.printData(BluetoothConnectionService.iPrinter, printBean)) {
                showToast("打印完成");
                AppHttp.getInstance().queryPrintResult(printBean.getParcelId());
            } else {
                showToast("打印失败");
            }
        } else {
            showToast("暂不支持该快递公司打印");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == Const.RequestCode.scan_bag) {
            String bagcode = data.getStringExtra("result");
            if (StringUtils.isEmpty(bagcode)) {
                return;
            }
            int index = bagcode.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = bagcode.substring(index + 1, bagcode.length());
            } else {
                code2 = bagcode;
            }
            showLoadingDialog(null);
            AppHttp.getInstance().queryParcelByBagCode(code2);
        } else if (requestCode == 102) {
            connectionDevice();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (BluetoothConnectionService.iPrinter != null) {
            BluetoothConnectionService.iPrinter.disconnect();
        }
    }
}
